package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/cncamp/golang_leaning/httpserver/metrics"
	"github.com/golang/glog"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"io"
	"log"
	"math/rand"
	"net/http"
	"net/http/pprof"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	flag.Parse()
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")
	//  注册延迟监控
	metrics.Register()

	mux := http.NewServeMux()
	mux.HandleFunc("/", rootHandler)
	mux.HandleFunc("/test", testHandler)

	mux.HandleFunc("/health/liveness", liveness)
	mux.HandleFunc("/health/readiness", readiness)

	mux.HandleFunc("/debug/pprof/", pprof.Index)
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)

	// 测试随机延迟
	mux.HandleFunc("/test-delay", delayTestHandler)
	// 采集metrics
	mux.Handle("/metrics", promhttp.Handler())

	srv := http.Server{
		Addr:    ":80",
		Handler: mux,
	}
	done := make(chan os.Signal, 1)
	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	log.Print("Server Started")
	<-done
	log.Print("Server Stopped")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		// extra handling here
		cancel()
	}()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server Shutdown Failed:%+v", err)
	}
	log.Print("Server Exited Properly")

}

func delayTestHandler(w http.ResponseWriter, r *http.Request) {
	glog.V(4).Info("entering root handler")
	timer := metrics.NewTimer()
	// 请求结束上报请求执行情况
	defer timer.ObserveTotal()
	user := r.URL.Query().Get("user")
	// 添加随机延迟
	delay := randInt(1,2000)
	time.Sleep(time.Millisecond*time.Duration(delay))
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello [stranger]\n")
	}
	io.WriteString(w, "===================Details of the http request header:============\n")
	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	glog.V(4).Infof("Respond in %d ms", delay)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("entering root handler")
	user := r.URL.Query().Get("user")
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello [stranger]\n")
	}
	io.WriteString(w, "===================Details of the http request header:============\n")
	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
}

func readiness(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "可以接收流量了\n")
	w.WriteHeader(200)
}

func liveness(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "ok, 我还活着\n")
	w.WriteHeader(200)
}

func testHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("entering test handler")
	// 1. 获取客户端通过head发送的token，响应服务器端的token
	clientHead := r.Header.Get("client_token")
	w.Header().Set("server_token", fmt.Sprintf("%s_%s", clientHead, time.Now()))

	// 2. 获取环境变量中的版本信息
	w.Header().Set("VERSION", os.Getenv("VERSION"))
	w.Header().Set("GOROOT", os.Getenv("GOROOT"))

	// 3. 输出内容
	msg := fmt.Sprintf("ip:%s，status：%d", r.RemoteAddr, 200)
	log.Print(msg)
	fmt.Println(msg)

	io.WriteString(w, "ok")
}


func randInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}